<!-- 登录页面 -->
<template>
	<view>
		<view class="loginLogo">
			<form @submit="onSubmit(true, $event)" class="loginContent">
				<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
					<image class="avatar"
						:src="formData.avatarUrl?formData.avatarUrl:'/static/tx.png'">
					</image>
					<text class="loginLogoText" v-if="isShow">授权头像</text>
				</button>
				<view class="nameContent">
					<view class="title">昵称</view>
					<input name="nickName" type="nickname" placeholder="请填写昵称" class="weui-input"
						v-model="formData.nickName" />
				</view>
 
				<view class="loginBtn" >
					<button class="btn" form-type="submit" open-type="getPhoneNumber"
						@getphonenumber="getPhoneNumber">手机号一键登录</button>
				</view>
			</form>
		</view>
 
	</view>
</template>
 
<script>
	import { mapMutations,mapState } from 'vuex'
	export default {
		data() {
			return {
				iv: "",
				encryptedData: '',
				phoneNum: "",
				openId: '',
				formData: {
					nickName: '',
					avatarUrl: ''
				},
				isShow: true,
				token: "",
				//是否显示手机号登录,如果根据昵称和头像能得到userId,就不用显示获取手机号的按钮，如果得不到，就显示这个按钮
				isShowPhone: false
			}
		},
		computed: {
			...mapState('m_user', ['redirectInfo']),
			...mapState('m_user', ['userId']),
		},
		watch: {
			formData: {
				handler(newVal, oldValue) {
					if (newVal.avatarUrl) {
						this.isShow = false;//监测isShow，如果授权头像了就隐藏 授权头像 字样
					}
				},
				deep: true,
				immediate: true
			}
		},
		methods: {
			...mapMutations('m_user', ['updateUserInfo']),
			...mapMutations('m_ws', ['updateWsTaskId']),
			...mapMutations('m_user', ['updateUserId']),
			
			updateUserAllInfoData(v) {
				this.updateUserAllInfo(v);
			},
			//获取微信头像
			onChooseAvatar(e) {
				this.formData.avatarUrl = e.detail.avatarUrl;
				console.log("eeee", e.detail);
			},
			onSubmit(confirm, event) {
				if (confirm) {
					try {
						let {
							nickName
						} = event.detail.value;
						this.formData.nickName = nickName;
					} catch (e) {
						//TODO handle the exception
						uni.showToast({
							icon: 'none',
							title: e.message
						});
						return;
					}
				}
			},
			// 微信获取手机号信息
			getPhoneNumber(data) {
				if (this.formData.avatarUrl && this.formData.nickName) {
					//微信小程序返回的相关数据
					this.iv = data.detail.iv;
					this.encryptedData = data.detail.encryptedData;
					uni.showToast({
						title: '登录中',
						icon: 'loading',
						duration: 1000,
					});
					//处理头像链接
					this.uploadImage(this.formData.avatarUrl,data);
 
				} else {
					uni.showToast({
						title: `请选择头像或输入昵称~`,
						icon: 'none'
					});
				}
			},
			async uniLogin(e) {
				// 获取 code 对应的值
				const res= await uni.login()
				// const [err, res] = await uni.login().catch(err => err)
							
				if (res.errMsg !== 'login:ok') return uni.$showMsg('登录失败！')
				
				console.log("头像和昵称---", this.formData.avatarUrl, this.formData.nickName);
					//请求后台,获取openId
				await uni.request({
					url: uni.$http.baseUrl+'/wechatApplet/getStudentInfo',
					method: 'POST',
					data: {
						code: res.code,
						encryptedData: e.detail.encryptedData,
						iv: e.detail.iv
					},
					header: {
					//"Content-Type": "multipart/form-data",
						"Content-Type": "application/x-www-form-urlencoded"
					},
					//sslVerify: false,
					success: (res1) => {
						console.log("用户登录返回数据----", res1.data.data);
						this.openId = res1.data.data.openId;
						this.phoneNum = res1.data.mobile;
						//this.token = res1.data.data.user.access_token;
						let params = {
							sessionKey: res1.data.data.sessionKey,
							iv: this.iv,
							encryptedData: this.encryptedData,
							id: res1.data.data.openId,
						}
						//将openId、nickName、avatarUrl存储到本地
						// 存储OpenID
						uni.setStorage({
							key: 'openId',
							data: res1.data.data.openId,
							success: function() {
								console.log(
									'OpenID存储成功'
								);
							},
							fail: function(error) {
								console.error(
									'OpenID存储失败:',
									error);
							}
						});
						uni.setStorage({
							key: 'nickName',
							data: this.formData.nickName,
							success: function() {
								console.log(
									'nickName存储成功'
								);
							},
							fail: function(error) {
								console.error(
									'nickName存储失败:',
									error);
							}
						});
						uni.setStorage({
							key: 'avatarUrl',
							data: this.formData.avatarUrl,
							success: function() {
								console.log(
									'avatarUrl存储成功'
								);
							},
							fail: function(error) {
								console.error(
									'avatarUrl存储失败:',
									error);
							}
						});
						//将昵称和头像存数据库
						this.updateUserInfoToService(res1)
						this.getUserInfo(res1)
					}
				})
				 
				
			},
			async updateUserInfoToService(res){
				await uni.request({
					url: uni.$http.baseUrl+'/api/student/update',
					method: 'POST',
					data: {
						id: res.data.data.id,
							//昵称
						nickName: this.formData.nickName,
							//头像
						headerUrl: this.formData.avatarUrl
					},
					header: {
						"Content-Type": "application/json",
						//"Content-Type": "application/x-www-form-urlencoded"
					},
					//sslVerify: false,
					success: (res1) => {
						console.log("更新用户数据----", res1.data.data);
					},
					fail: (res) =>{
						if (res.statusCode !== 200) return uni.$showMsg()
					},
				});
				
			},
			//获取该登录用户的信息
			async getUserInfo(res) {
				//将用户信息存储进仓库
				res.data.data.nickName=this.formData.nickName
				res.data.data.headerUrl=this.formData.avatarUrl
				this.updateUserInfo(res.data.data)
				console.log(res.data.data.id)
				this.updateUserId(res.data.data.id)
				
 
				uni.showToast({
					title: `登陆成功~`,
					icon: 'none'
				});
 
				//跳转回个人中心页面
				setTimeout(() => {
					uni.switchTab({
						url: `/pages/myhome/myhome`,
						success() {
							var page = getCurrentPages().pop();
							if (page == undefined || page == null) return;
							page.onLoad();
						},
						fail(e) {
							console.error(e);
						}
					})
				}, 2000);
			},
			//头像图片持久化
			uploadImage(url1,data) {
				//uni.uploadFile将微信返回的临时地址转成文件流传输给后端，从而上传服务器，拿到永久地址
				uni.uploadFile({
					url: uni.$http.baseUrl+'/common/sysFile/upload',
					filePath: url1,
					name: 'file',
					header: {
						'content-type': 'application/x-www-form-urlencoded',
					},
					formData: {
						'user': this.formData.nickName
					},
					success: (uploadFileRes) => {
						this.formData.avatarUrl = JSON.parse(uploadFileRes.data).imgUrl;
 
						//进入登录流程
						this.uniLogin(data);
					}
				});
			},
		}
	}
</script>
 
<style scoped lang="scss">
	.avatar-wrapper {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		background: none;
		color: inherit;
		border: none;
		padding: 0;
		font: inherit;
		cursor: pointer;
		outline: inherit;
 
		.avatar {
			height: 120rpx;
			width: 120rpx;
			border-radius: 20rpx;
		}
	}
 
	.avatar-wrapper::after {
		border: none;
	}
 
	.nameContent {
		display: flex;
		margin: 70rpx 0;
		border-top: 1px solid #eee;
		border-bottom: 2rpx solid #eee;
		padding: 20rpx 40rpx;
		width: 100vw;
		box-sizing: border-box;
		font-size: 28rpx;
		align-items: center;
 
		.title {
			margin-right: 40rpx;
		}
	}
 
	.loginLogo {
		height: 700rpx;
		display: flex;
		justify-content: center;
		align-items: center;
 
		.loginContent {
			display: flex;
			justify-content: center;
			align-items: center;
			flex-direction: column;
			width: 100%;
 
			.loginLogoText {
				font-size: 24rpx;
				color: #828282;
				margin-top: 20rpx;
			}
		}
	}
 
	.loginBtn {
		width: 100%;
 
		.btn {
			width: 80%;
			border-radius: 20rpx;
			background-color: #ee3236;
			color: white;
		}
	}
</style>